package it.agm.fanta.asynctask.jersey.patch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;




//import com.agm.dto.Utente;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.jersey.spi.service.ServiceFinder;

public class NetworkHandler {

	private static NetworkHandler instance;

	public static synchronized NetworkHandler getInstance() {
		if (instance == null) {
			instance = new NetworkHandler();
		}
		return instance;
	}

	@SuppressWarnings("rawtypes")
	private NetworkHandler() {
		ServiceFinder.setIteratorProvider(new AndroidServiceIteratorProvider());
	}

	public <T> void read(final String url, final Class<T> clazz,
			final Callback<T> callback) {
		 new GetTask(url, new Callback<String>() {
			 
		      @Override
		      public void callback(String result) {
		        callback.callback(new GsonBuilder().create().fromJson(result, clazz));
		      }
		    }).execute();
	}

	public <T> void readList(final String url, final Class<T[]> clazz,
			final Callback<List<T>> callback) {
		 new GetTask(url, new Callback<String>() {
			 
		      @Override
		      public void callback(String result) {
		        final T[] array = new GsonBuilder().create().fromJson(result, clazz);
		        callback.callback(new ArrayList<T>(Arrays.asList(array)));
		      }
		    }).execute();
	}

	public <T> void write(final String url, final Class<T> clazz, final T t,
			final Callback<T> callback) {
		final Gson gson = new GsonBuilder().create();
			new PostTask(url, gson.toJson(t), new Callback<String>() {

				@Override
				public void callback(String result) {
					ObjectMapper mapper = new ObjectMapper();
					try {
						callback.callback(mapper.readValue(result, clazz));
					} catch (Throwable e) {
						e.printStackTrace();
					}
				}
			}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

	}
	
	public static boolean checkConnection(Context context) {

	    final ConnectivityManager mConnectivityManager = (ConnectivityManager) context
	            .getSystemService(Context.CONNECTIVITY_SERVICE);

	    final NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    } else
	        return false;
	 }
}
